package top.frsf.pattern.a_creational.a_singleton;

/**
 * @Author He Kuntao
 * @Date 2024/7/2 14:38
 * @Desc 单例模式 -- 懒汉实现
 **/
public class Singleton2 {

  private volatile static Singleton2 singleton2;

  private Singleton2(){}

  /**
   * new并非原子性 1.分配内存 2.初始化对象 3.设置引用
   * 同步锁防止多线程访问 -- 双重检查锁
   */
  public static Singleton2 getInstance() {
    if (singleton2 == null) {
      synchronized (Singleton2.class) {
        if (singleton2 == null) {
          singleton2 = new Singleton2();
        }
      }
    }
    return singleton2;
  }
}
